//@ts-ignore
import getMessage from 'ts-msg-handler'
import { GlobalData } from '/store/state'
import { mallApi } from '/api/mall'
import { $event } from '/utils'
import { getUser } from '/store/actions'

enum TypeEnum {
  appeal = 'appeal', // 申请投诉
  feedback = 'feedback', // 咨询反馈
  refund = 'refund', // 退款
  return = 'return', // 退货
  negotiate = 'negotiate', // 协商
}
enum DisableEnum {
  appeal = 'appeal', // 禁用申请投诉
  feedback = 'feedback', // 禁用咨询反馈
}

interface QueryOptions {
  orderId?: number
  type?: TypeEnum
  shopkeeper?: boolean
  disable?: DisableEnum
}

Page({
  data: {
    orderId: 0,
    type: '' as string,
    shopkeeper: false,
    orderInfo: {} as any,
    localImages: [] as Array<{ url: string; node?: string }>,
    showHistory: false,
    lock: false,
    currencyName: GlobalData.currencyName,
    // 是否可以申请协商退款
    canApplyReturnOrRefund: false,

    // 控制页面元素显示
    pageControl: {
      navigateTitle: '', // 导航栏标题
      inputTitle: '', // 输入框上方标题
    },
  },
  async onLoad(query: QueryOptions) {
    this.setData(
      {
        orderId: query.orderId,
        type: query.type,
        shopkeeper: !!query.shopkeeper,
        radioDisable: query.disable,
      },
      this.computedPage,
    )
  },
  async onShow() {
    const pages = getCurrentPages()
    const orderInfo = pages[pages.length - 2].data.orderInfoTemp
    this.setData({
      orderInfo,
      currencyName: GlobalData.currencyName,
      canApplyReturnOrRefund: GlobalData.mall.refund_count > orderInfo.refund_count,
    })
  },
  computedPage() {
    const { type, pageControl } = this.data

    switch (type) {
      case 'appeal':
      case 'feedback':
        pageControl.navigateTitle = '联系平台'
        break
      case 'refund':
        pageControl.navigateTitle = '退款进度'
        pageControl.inputTitle = '退款申请'
        break
      case 'return':
        pageControl.navigateTitle = '退货进度'
        pageControl.inputTitle = '退货申请'
        break
      case 'negotiate':
        pageControl.navigateTitle = '协商退款进度'
        pageControl.inputTitle = '协商退款申请'
        break
    }
    this.setData({ pageControl })
    wx.setNavigationBarTitle({ title: pageControl.navigateTitle })
  },
  /** 预览图片 */
  showImages(e: any) {
    const { images, index } = e.currentTarget.dataset
    wx.previewImage({
      urls: images.map((item: any) => item.url),
      current: images[index].url,
    })
  },
  toDetail(event: WechatMiniprogram.BaseEvent) {
    const data = event.currentTarget.dataset as { id: number; orderId: number }
    wx.navigateTo({ url: `/mall/detail/detail?commodityId=${data.id}&orderId=${data.orderId}` })
  },
  // 买家发货
  writeShip() {
    GlobalData.shipInfo.retId = this.data.orderInfo.refund ? this.data.orderInfo.refund.id : ''
    wx.navigateTo({ url: `/mall/fillShipInfo/fillShipInfo?buyer=1` })
  },
  logisticsDetail(e: WechatMiniprogram.CustomEvent) {
    const info = JSON.stringify(e.currentTarget.dataset.logistics)
    wx.navigateTo({
      url: `/mall/logisticsInfo/logisticsInfo?id=${this.data.orderId}&info=${info}`,
    })
  },
  toggleHistory() {
    this.setData({ showHistory: !this.data.showHistory })
  },
  async optionHandle(e: any) {
    const { type } = e.currentTarget.dataset
    const { orderInfo } = this.data
    try {
      wx.showLoading({ title: '处理中' })
      switch (type) {
        case 'cancel': // 买家取消退款/退货申请
          await mallApi.cancelRefund(orderInfo.refund.id)
          break
        case 'agree_refund': // 商家同意退款申请
          await mallApi.agreeRefund(orderInfo.refund.id)
          break
        case 'agree_returned': // 商家拦截发货并退款
          await mallApi.interceptRefund(orderInfo.refund.id)
          break
        case 'confirm_refund': // 商家确认收货并退款
          await mallApi.confirmRefund(orderInfo.refund.id)
          break
        case 'confirm_negotiate': // 卖家确认收货需协商价格
          await mallApi.negotiateRefund(orderInfo.refund.id)
          break
        case 'agree_negotiate': // 协商-商家同意退款申请
          await mallApi.agreeRefundNegotiate(orderInfo.refund.negotiates[0].id)
          break
      }

      $event.emit('mallOrderChange')
      wx.showToast({ title: '操作成功' })
      setTimeout(() => {
        wx.navigateBack({ delta: 1 })
      }, 1000)
    } catch (error) {
      console.log(error)
      wx.showToast({
        title: `${getMessage(error.data).getMessage() || '操作失败'}`,
        icon: 'none',
      })
      wx.hideLoading()
      this.setData({ lock: false })
    }
  },
  async toPage(e: any) {
    const { type } = e.currentTarget.dataset
    const { orderId, orderInfo } = this.data
    switch (type) {
      case 'refuse_refund': // 商家拒绝退款申请
        wx.navigateTo({
          url: `/mall/form/index?type=refuse_refund&orderId=${orderId}&retId=${orderInfo.refund ? orderInfo.refund.id : ''
            }`,
        })
        break
      case 'agree_return': // 商家同意退货申请
        wx.navigateTo({
          url: `/mall/fillShipAddress/index?type=agree_return&orderId=${orderId}&retId=${orderInfo.refund ? orderInfo.refund.id : ''
            }`,
        })
        break
      case 'refuse_return': // 商家拒绝退货申请
        wx.navigateTo({
          url: `/mall/form/index?type=refuse_return&orderId=${orderId}&retId=${orderInfo.refund ? orderInfo.refund.id : ''
            }`,
        })
        break
      case 'negotiate': // 协商退款
        wx.navigateTo({
          url: `/mall/form/index?type=negotiate&orderId=${orderId}&retId=${orderInfo.refund ? orderInfo.refund.id : ''
            }`,
        })
        break
      case 'refuse_negotiate': // 协商-商家拒绝退款申请
        wx.navigateTo({
          url: `/mall/form/index?type=refuse_negotiate&orderId=${orderId}&retId=${orderInfo.refund ? orderInfo.refund.id : ''
            }&neoId=${orderInfo.refund && orderInfo.refund.negotiates && orderInfo.refund.negotiates.length
              ? orderInfo.refund.negotiates[0].id
              : ''
            }`,
        })
        break
    }
  },
  // 申请协商退款
  async applyNegotiate(e: any) {
    const { type } = e.currentTarget.dataset
    await getUser()
    const { orderInfo } = this.data
    const text = type === 'refund' ? '退款' : type === 'return' ? '退货' : '协商退款'
    if (orderInfo.refund_count >= GlobalData.mall.refund_count) {
      wx.showToast({
        title: '申请次数已用完',
        icon: 'error',
      })
      return
    }

    let desc = ''
    if (orderInfo.refund_count === 0) {
      // 第一次机会
      desc = `买家退货、退款、协商退款申请被驳回后可再次申请，共有${GlobalData.mall.refund_count}次机会。若买家在申请审核的过程中取消申请，也会计入申请次数`
    } else if (GlobalData.mall.refund_count - GlobalData.mall.refund_count === 1) {
      // 最后一次
      desc = `你共有${GlobalData.mall.refund_count}次申请退款、退货、协商退款的机会，这是你第${orderInfo.refund_count + 1
        }次申请，申请被驳回后，你将不能再提交`
    } else {
      // 中间的
      desc = `你共有${GlobalData.mall.refund_count}次申请退款、退货、协商退款的机会，这是你第${orderInfo.refund_count + 1
        }次申请， 是否继续申请？`
    }

    $event.emit('showSheet', [
      {
        title: `${text}提示`,
        desc,
        enableBottom: true,
        fontWeight: true,
      },
      {
        title: `申请${text}`,
        url: `/mall/form/index?type=${type}&orderId=${orderInfo.id}&retId=${orderInfo.refund ? orderInfo.refund.id : ''
          }&shopkeeper=${this.data.shopkeeper ? '1' : ''}`,
      },
    ])
  },
})
